/**
 * Copyright (c) 2018, 西安星沙网络科技-版权所有
 *
 * Licensed under the GNU Lesser General Public License (LGPL) ,Version 3.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.gnu.org/licenses/lgpl-3.0.txt
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.waleychain.exchange.schedule.task;

import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONObject;

import cn.waleychain.exchange.core.constant.WSConstant;
import cn.waleychain.exchange.core.entity.KLineUser;
import cn.waleychain.exchange.core.logger.LoggerHelper;
import cn.waleychain.exchange.service.trade.KLineService;
import cn.waleychain.exchange.service.trade.TradeDataService;

/**
 * k线图数据调度
 * @author chenx
 * @date 2018年4月23日 上午9:44:37
 * @version 1.0 
 */
@Component
public class KLineDataTask {

	private static final Logger mLog = LoggerFactory.getLogger(TradeOrderProcessTask.class);
	
	@Autowired
    private SimpMessagingTemplate template;
	
	@Autowired
	private TradeDataService tradeDataService;
	
	@Autowired
	private KLineService kLineService;
	
	@Scheduled(fixedDelay = 5000) // 延迟1000毫秒执行
	public void handler() {
		try {
			
			List<KLineUser> kuserList = tradeDataService.fetchKLineUserList();
			if (kuserList == null || kuserList.size() <= 0) {
				return;
			}
		
			Iterator<KLineUser> iter = kuserList.iterator();
			while (iter.hasNext()) {
				KLineUser kuser = iter.next();
				
				Map<String, Object> data = kLineService.fetchKLineData(kuser.getMarketId(), kuser.getDataType(), kuser.getkLimit());
				
				// 消息推送
				template.convertAndSendToUser(kuser.getSessionId(), WSConstant.p2pKlineListenerPath, JSONObject.toJSONString(data));
			}
		
		} catch (Exception e) {
			LoggerHelper.printLogErrorNotThrows(mLog, null, "根据交易对ID获取最新50笔成交记录，并保存到内存中：" + e.getMessage());
		}
	}
}
